package g

import (
	"go-monitor/common/utility"
	"log"
	"net"
	"os"
	"time"

	"github.com/astaxie/beego/logs"
	net1 "github.com/toolkits/net"
	"path"
)

var Logger *logs.BeeLogger

func init() {
	InitRootDir()
	InitLog()
}

var Root string

func InitRootDir() {
	var err error
	Root, err = os.Getwd()
	if err != nil {
		log.Println("getwd fail:", err)
		os.Exit(1)
	}
}

func InitLog() {
	logdir := Root + "/var/log/"
	if !utility.PathExists(logdir) {
		err := os.MkdirAll(logdir, os.ModeDir)
		if err != nil {
			log.Println("log dir create fail")
			os.Exit(1)
		}
	}
	Logger = logs.NewLogger(100000)
	Logger.SetLogger(logs.AdapterFile, `{"filename":`+path.Join(logdir+"run.log")+`}`)
	Logger.SetLogger(logs.AdapterConsole)
	Logger.EnableFuncCallDepth(true)
}

var LocalIps []string
var NetworkIp string

//需判断是否本地，线上agent获取外网IP
func InitLocalIps() {
	if Config().Host == "local" {
		var err error
		LocalIps, err = net1.IntranetIP()
		if err != nil {
			Logger.Error("get intranet ip fail:", err)
		}
	} else {
		addrs, err := net.InterfaceAddrs()
		if err != nil {
			Logger.Error("net.InterfaceAddrs err:", err)
			os.Exit(1)
		}
		count := 0
		for _, address := range addrs {
			// 检查ip地址判断是否回环地址
			if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
				if ipnet.IP.To4() != nil {
					if count == 1 {
						NetworkIp = ipnet.IP.String()
					}
					count++
				}
			}
		}
	}
}

var (
	RPCClient *SingleConnRPCClient
)

// InitRPCClients 初始化RPC客户端请求参数
func InitRPCClients() {
	if Config().RPCServer.Enabled {
		RPCClient = &SingleConnRPCClient{
			RPCServer: Config().RPCServer.Addr,
			Timeout:   time.Duration(Config().RPCServer.Timeout) * time.Millisecond,
		}
	}
}
